package com.sec.etech.employeesync.confighandler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sec.etech.employeesync.entity.OrgEmployeeZLearningForm;
import com.sec.etech.employeesync.mapper.OrgEmployeeZLearningFormMapper;
import com.sec.etech.employeesync.util.ConfigTableHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

@Component
@Slf4j
public class LearningFormConfigHandler implements ConfigTableHandler<OrgEmployeeZLearningForm> {

    @Resource
    private OrgEmployeeZLearningFormMapper learningFormMapper;

    @Override
    public Long getOrCreateConfigId(String... params) {
        String code = params[0];
        OrgEmployeeZLearningForm learningForm = getEntityByName(code);
        if (learningForm == null) {
            return null;
        }
        return learningForm.getLearningFormId();
    }

    @Override
    public OrgEmployeeZLearningForm getEntityByName(String code) {
        return learningFormMapper.selectOne(Wrappers.<OrgEmployeeZLearningForm>lambdaQuery()
                .eq(OrgEmployeeZLearningForm::getCode, code));
    }

    @Override
    public String generateNextCode() {
        OrgEmployeeZLearningForm politics = learningFormMapper.selectOne(Wrappers.<OrgEmployeeZLearningForm>lambdaQuery()
                .orderByDesc(OrgEmployeeZLearningForm::getCode)
                .last("limit 1"));

        String lastCode = Optional.ofNullable(politics)
                .map(OrgEmployeeZLearningForm::getCode)
                .orElse("0");

        return generateNextCode(lastCode);
    }

    @Override
    public void insertEntity(OrgEmployeeZLearningForm entity) {
        learningFormMapper.insert(entity);
    }
}
